package com.longcheng.sensordemo;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

import com.longcheng.sensordemo.constants.MyConstants;

public class SecondActivity extends AppCompatActivity {
    private EditText mEditText;
    private SensorManager mSensorManager;
    /**
     * 监听的传感器的类型,从MainActivity传递过来的
     */
    private int mSensorType;
    private SensorEventListener mSensorListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        mEditText = (EditText) findViewById(R.id.editText);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        //获取mSensorType
        mSensorType = getIntent().getIntExtra(MyConstants.type,
                Sensor.TYPE_LINEAR_ACCELERATION);
        setListener();
    }

    private void setListener() {
        mSensorListener = new SensorEventListener() {
            /**
             * @param event : 监听返回的传感器的值都在event里
             */
            @Override
            public void onSensorChanged(SensorEvent event) {
                float[] values = event.values;
                switch (mSensorType) {
                    case Sensor.TYPE_LINEAR_ACCELERATION://线性加速度:
                        StringBuilder builder = new StringBuilder();
                        builder.append("x轴:");
                        builder.append(values[0]);
                        builder.append("\n");
                        builder.append("y轴:");
                        builder.append(values[1]);
                        builder.append("\n");
                        builder.append("z轴:");
                        builder.append(values[2]);
                        mEditText.setText(builder.toString());
                        break;
                    case Sensor.TYPE_LIGHT://光线
                        break;
                    case Sensor.TYPE_PROXIMITY://接近
                        break;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };
        //注册监听事件
        mSensorManager.registerListener(
                mSensorListener,
                mSensorManager.getDefaultSensor(mSensorType),
                SensorManager.SENSOR_DELAY_FASTEST);

    }

    /**
     * 界面销毁时需要反注册监听
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(mSensorListener);
    }
}
